﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode, ImageEffectAllowedInSceneView]
public class ScreenWaterEffect : MonoBehaviour
{
    public Texture rainTex;
    private Material mat;

    //时间变量和素材图的定义
    private float TimeX = 1.0f;//时间变量

    //可以在编辑器中调整的参数值
    [Range(5, 64), Tooltip("溶解度")]
    public float Distortion = 8.0f;
    [Range(0, 7), Tooltip("水滴在X坐标上的尺寸")]
    public float SizeX = 1f;
    [Range(0, 7), Tooltip("水滴在Y坐标上的尺寸")]
    public float SizeY = 0.5f;
    [Range(0, 10), Tooltip("水滴的流动速度")]
    public float DropSpeed = 1f;

    [System.Obsolete]
    void Start()
    {
        //判断是否支持屏幕特效
        if (!SystemInfo.supportsImageEffects)
        {
            this.enabled = false;
        }

        if (mat == null)
        {
            mat = new Material(Shader.Find("Custom/ScreenWaterDrop"));
            mat.SetTexture("_ScreenWaterDropTex", rainTex);
        }
    }

    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (mat == null)
        {
            mat = new Material(Shader.Find("Custom/ScreenWaterDrop"));
            mat.SetTexture("_ScreenWaterDropTex", rainTex);
            Graphics.Blit(source, destination);
            return;
        }

        //时间的变化
        TimeX += Time.deltaTime;
        //时间大于100，便置0，保证可以循环
        if (TimeX > 100) TimeX = 0;

        //设置Shader中其他的外部变量
        mat.SetFloat("_CurTime", TimeX);
        mat.SetFloat("_Distortion", Distortion);
        mat.SetFloat("_SizeX", SizeX);
        mat.SetFloat("_SizeY", SizeY);
        mat.SetFloat("_DropSpeed", DropSpeed);
        mat.SetTexture("_ScreenWaterDropTex", rainTex);

        Graphics.Blit(source, destination, mat);
    }

    void OnDisable()
    {
        if (mat)
        {
            DestroyImmediate(mat);
        }

    }
}
